/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.istia.gesstages.dao.db;

import fr.istia.gesstages.dao.IDaoApply;
import fr.istia.gesstages.exception.PortailException;
import fr.istia.gesstages.jpa.Apply;
import fr.istia.gesstages.jpa.Offer;
import fr.istia.gesstages.jpa.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

/**
 * @date 22/11/2011
 * @author Cédric Moreau
 */
@Transactional
public class DaoApplyDB implements IDaoApply {

    @PersistenceContext
    private EntityManager em;

    public Apply create(Apply apply) {
        try {
            em.persist(apply);
            return apply;
        } catch (Exception e) {
            throw new PortailException("Erreur lors de la création du candidature", e);
        }
    }

    public Apply update(Apply apply) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Apply delete(Apply apply) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Apply findBy(Offer offer, User student) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public List<Apply> findBy(Offer offer) {
        try {
            return em.createQuery("select c from Apply c where c.stage.id = " + offer.getId()).getResultList();
        } catch (Exception e) {
            throw new PortailException(" Erreur lors de la recuperation des candidatures de l'offre n°" + offer.getId(), e);
        }
    }

    public List<Apply> findBy(User student) {
        try {
            return em.createQuery("select a from Apply a where a.user.id = " + student.getId()).getResultList();
        } catch (Exception e) {
            throw new PortailException("Erreur lors de la recuperation des candidatures de l'utilisateur '" + student.getLogin() + "'", e);
        }
    }

    public void deleteAll() {
        try {
            em.createQuery("DELETE FROM Apply a").executeUpdate();
        } catch (Exception e) {
            throw new PortailException("Erreur lors de la suppression de toutes les candidatures", e);
        }
    }
}
